package com.snk.kof.common.utils;


import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;

import java.util.Collection;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * @author keshan
 * @date 2021-02 下午8:23
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Executor {

    private static final Executor EXECUTOR = new Executor();

    public static Executor get() {
        return EXECUTOR;
    }

    public <T> Executor exec(T t, Predicate<T> predicate, Consumer<T> trueConsumer, Consumer<T> falseConsumer) {
        if (predicate.test(t)) {
            trueConsumer.accept(t);
        } else {
            falseConsumer.accept(t);
        }
        return this;
    }

    public <T> Executor exec(T t, Predicate<T> predicate, Consumer<T> trueConsumer, Supplier<RuntimeException> supplier) {
        if (!predicate.test(t)) {
            throw supplier.get();
        }
        trueConsumer.accept(t);
        return this;
    }

    public <T> Executor execIfNotNull(T t, Consumer<T> consumer) {
        return execIf(t, Objects::nonNull, consumer);
    }

    public <T> Executor execIfNotEmpty(Collection<T> t, Consumer<T> consumer) {
        return execIf(t, CollectionUtils::isNotEmpty, o -> o.forEach(consumer));
    }

    public <T> Executor execIf(T t, Predicate<T> predicate, Consumer<T> consumer) {
        if (predicate.test(t)) {
            consumer.accept(t);
        }
        return this;
    }

}
